package task;

import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.ui.JBColor;
import org.apache.http.util.TextUtils;

import java.awt.*;

public class TaskRunner extends Thread{

    private  Editor editor;

    public TaskRunner(Editor editor){
        this.editor = editor;
        super.setDaemon(true);
    }

    private void showPopupBalloon(final Editor editor, final String result) {
        ApplicationManager.getApplication().invokeLater(new Runnable() {
            public void run() {
                JBPopupFactory factory = JBPopupFactory.getInstance();
                factory.createHtmlTextBalloonBuilder(result, null, new JBColor(new Color(186, 238, 186), new Color(73, 117, 73)), null)
                        .setFadeoutTime(5000)
                        .createBalloon()
                        .show(factory.guessBestPopupLocation(editor), Balloon.Position.below);
            }
        });
    }



    @Override
    public void run() {
        while (true){
            System.err.println("loop");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (null == this.editor) {
                continue;
            }

            SelectionModel model = this.editor.getSelectionModel();

            final String selectedText = model.getSelectedText();
            if (TextUtils.isEmpty(selectedText)) {
                continue;
            }

            showPopupBalloon(this.editor,selectedText);
        }
    }
}
